package com.example.poemtest;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;


import com.example.poemtest.Activity.LoginActivity;
import com.example.poemtest.entity.PoetryInfoBean;
import com.example.poemtest.entity.PostInfoBean;
import com.example.poemtest.entity.PropInfoBean;
import com.example.poemtest.entity.DynastryPoetryBean;
import com.example.poemtest.mine.HelpActivity;
import com.example.poemtest.mine.MyFavouriteActivity;
import com.example.poemtest.mine.MyPoetryCreationActivity;
import com.example.poemtest.mine.MyPostActivity;
import com.example.poemtest.mine.MyPropActivity;
import com.example.poemtest.mine.SetupActivity;
import com.example.poemtest.mine.UpdateActivity;
import com.example.poemtest.utils.Constant;
import com.example.poemtest.utils.FullScreenUtil;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * created by JHT on 2024/1/19
 * 我的页面fragment
 */
public class MineFragment extends Fragment implements View.OnClickListener {

    // 声明变量
    private View root;
    private ImageButton mineLoginOut;
    private TextView mineUserName, mineJifen, userLevel;
    private LinearLayout mineShoucang, mineShidan, mineDaoju;
    private RelativeLayout mineCitie, mineSecret, mineHelp, mineUpdate, mineSetup;
    private CircleImageView circleImageView;
    private int code;   //返回的状态码
    private String msgCon;  //返回的错误信息
    private Handler myHandler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //处理子线程发送的消息
            String result = (String) msg.obj;
            int flag = msg.arg1;
            if (flag == 0) {
                //获取用户购买的道具
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    code = jsonObject.getInt("code");
                    msgCon = jsonObject.getString("msg");
                    Log.e("状态码",code+"");
                    Log.e("返回的提示信息：",msgCon);
                    if (code == 200){
                        //解析json文件流
                        PropInfoBean propInfoBean = com.alibaba.fastjson.JSONObject.parseObject(result,PropInfoBean.class);
                        List<PropInfoBean.PropInfo> list = propInfoBean.getData();
                        if (Constant.myPropList.size() != 0) {
                            Constant.myPropList.clear();
                        }
                        for (PropInfoBean.PropInfo propInfo : list) {
                            Constant.myPropList.add(propInfo);
                        }
//                        for (PropInfoBean.PropInfo propInfo : Constant.myPropList) {
//                            Log.e("收到的道具数据",propInfo.toString());
//                        }
                    } else {
//                    Toast.makeText(getActivity().this,msgCon,Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (flag == 1) {
                //获取用户收藏的诗词
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    code = jsonObject.getInt("code");
                    msgCon = jsonObject.getString("msg");
                    Log.e("状态码",code+"");
                    Log.e("返回的提示信息：",msgCon);
                    if (code == 200){
                        //解析json文件流
                        DynastryPoetryBean dynastryPoetryBean = com.alibaba.fastjson.JSONObject.parseObject(result,DynastryPoetryBean.class);
                        List<DynastryPoetryBean.DynastyPoetry> list = dynastryPoetryBean.getData();
                        if (Constant.favPoetry.size() != 0) {
                            Constant.favPoetry.clear();
                        }
                        for (DynastryPoetryBean.DynastyPoetry dynastyPoetry : list) {
                            Constant.favPoetry.add(dynastyPoetry);
                        }
                    } else {
//                    Toast.makeText(getActivity().this,msgCon,Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (flag == 2) {
                //获取用户创作的诗
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    code = jsonObject.getInt("code");
                    msgCon = jsonObject.getString("msg");
                    Log.e("状态码",code+"");
                    Log.e("返回的提示信息：",msgCon);
                    if (code == 200){
                        //解析json文件流
                        PoetryInfoBean poetryInfoBean = com.alibaba.fastjson.JSONObject.parseObject(result,PoetryInfoBean.class);
                        List<PoetryInfoBean.PoetryInfo> list = poetryInfoBean.getData();
                        if (Constant.writePoetryList.size() != 0) {
                            Constant.writePoetryList.clear();
                        }
                        for (PoetryInfoBean.PoetryInfo poetryInfo : list) {
                            Constant.writePoetryList.add(poetryInfo);
                        }
                    } else {
//                    Toast.makeText(getActivity().this,msgCon,Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (flag == 3) {
                //获取用户发布的词帖
                Log.e("flag=",flag + "");
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    code = jsonObject.getInt("code");
                    msgCon = jsonObject.getString("msg");
                    Log.e("状态码",code+"");
                    Log.e("返回的提示信息：",msgCon);
                    if (code == 200){
                        //解析json文件流
                        PostInfoBean postInfoBean = com.alibaba.fastjson.JSONObject.parseObject(result,PostInfoBean.class);
                        List<PostInfoBean.PostInfo> list = postInfoBean.getData();
                        if (Constant.myCreatePostList.size() != 0) {
                            Constant.myCreatePostList.clear();
                        }
                        for (PostInfoBean.PostInfo postInfo : list) {
                            Constant.myCreatePostList.add(postInfo);
                        }
                        //打印一下信息
                        for (PostInfoBean.PostInfo postInfo : Constant.myCreatePostList) {
                            Log.e("我创建的词帖",postInfo.toString());
                        }
                    } else {
//                    Toast.makeText(getActivity().this,msgCon,Toast.LENGTH_LONG).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }
    };


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        FullScreenUtil.getInstance().fullScreen(getActivity(),true);
        root = inflater.inflate(R.layout.fragment_mine, container, false);
        //绑定控件对象
        initView();
        //设置数据
        setData();
        //获取用户已经购买的道具
        getCoon();
        //获取用户收藏的诗词
        getCoon1();
        //获取用户创作的诗
        getCoon2();
        //获取用户发布的词帖
        getCoon3();
        return root;

    }

    /**
     * 设置数据
     */
    private void setData() {
        mineJifen.setText(Constant.userGrade + "");
        mineUserName.setText(Constant.userName);
        String str = Constant.userPhoto;
//        Uri uri = Uri.parse(str);
//        viewHolder.propImg.setImageURI(uri);
        Picasso.get().load(str).into(circleImageView);
        userLevel.setText(Constant.userLevel + "");

    }

    /**
     * 绑定控件对象
     */
    private void initView() {
        circleImageView = root.findViewById(R.id.mine_img);
        mineUserName = root.findViewById(R.id.mine_user_name);
        mineJifen = root.findViewById(R.id.mine_jifen);
        userLevel = root.findViewById(R.id.mine_dengji);
        mineLoginOut = root.findViewById(R.id.mine_login_out);
        mineLoginOut.setOnClickListener(this);
        mineShoucang = root.findViewById(R.id.mine_shoucang);
        mineShoucang.setOnClickListener(this);
        mineShidan = root.findViewById(R.id.mine_shidan);
        mineShidan.setOnClickListener(this);
        mineDaoju = root.findViewById(R.id.mine_daoju);
        mineDaoju.setOnClickListener(this);
        mineCitie = root.findViewById(R.id.mine_citie);
        mineCitie.setOnClickListener(this);
        mineSecret = root.findViewById(R.id.mine_secret);
        mineSecret.setOnClickListener(this);
        mineHelp = root.findViewById(R.id.mine_help);
        mineHelp.setOnClickListener(this);
        mineUpdate = root.findViewById(R.id.mine_update);
        mineUpdate.setOnClickListener(this);
        mineSetup = root.findViewById(R.id.mine_setup);
        mineSetup.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.mine_login_out:
                //点击取消登录
                Intent intent = new Intent(MineFragment.this.getActivity(), LoginActivity.class);
                startActivity(intent);
                break;
            case R.id.mine_shoucang:
                //点击我的收藏
                Intent intent1 = new Intent(MineFragment.this.getActivity(), MyFavouriteActivity.class);
                startActivity(intent1);
                break;
            case R.id.mine_shidan:
                //点击我的诗单
                Intent intent3 = new Intent(MineFragment.this.getActivity(), MyPoetryCreationActivity.class);
                startActivity(intent3);
                break;
            case R.id.mine_daoju:
                //点击我的道具
                Intent intent4 = new Intent(MineFragment.this.getActivity(), MyPropActivity.class);
                startActivity(intent4);
                break;
            case R.id.mine_citie:
                //点击我的词帖
                Intent intent2 = new Intent(MineFragment.this.getActivity(), MyPostActivity.class);
                startActivity(intent2);
                break;
            case R.id.mine_secret:
                //点击隐私管理

                break;
            case R.id.mine_help:
                //点击帮助与客服
                Intent intent7 = new Intent(MineFragment.this.getActivity(), HelpActivity.class);
                startActivity(intent7);
                break;
            case R.id.mine_update:
                //点击检查更新
                Intent intent8 = new Intent(MineFragment.this.getActivity(), UpdateActivity.class);
                startActivity(intent8);
                break;
            case R.id.mine_setup:
                //点击设置
                Intent intent9 = new Intent(MineFragment.this.getActivity(), SetupActivity.class);
                startActivity(intent9);
                break;
            default:
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        setData();
    }

    /**
     * 获取用户已经购买的道具
     */
    private void getCoon(){
        //创建okhtto请求的对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建请求连接，url里面存放请求连接，get表示其实get请求
//        Request request = new Request.Builder()
//                .url("http://192.168.43.131:8080/userInfo/login")
//                .post(requestBody)
//                .build();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/propInfo/findPropByUserId?userId=" + Constant.userId)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                message.arg1 = 0;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

    /**
     * 获取用户收藏的诗
     */
    private void getCoon1(){
        //创建okhtto请求的对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建请求连接，url里面存放请求连接，get表示其实get请求
//        Request request = new Request.Builder()
//                .url("http://192.168.43.131:8080/userInfo/login")
//                .post(requestBody)
//                .build();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/dynastyPoetry/findFavPoetry?userId=" + Constant.userId)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                message.arg1 = 1;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

    /**获取用户创作的诗
     */
    private void getCoon2(){
        //创建okhtto请求的对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建请求连接，url里面存放请求连接，get表示其实get请求
//        Request request = new Request.Builder()
//                .url("http://192.168.43.131:8080/userInfo/login")
//                .post(requestBody)
//                .build();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/poetryInfo/findPoetryByUserId?userId=" + Constant.userId)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                message.arg1 = 2;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

    /**获取用户发布的词帖
     */
    private void getCoon3(){
        //创建okhtto请求的对象
        OkHttpClient okHttpClient = new OkHttpClient();
        //创建请求连接，url里面存放请求连接，get表示其实get请求
//        Request request = new Request.Builder()
//                .url("http://192.168.43.131:8080/userInfo/login")
//                .post(requestBody)
//                .build();
        Request request = new Request.Builder()
                .url("http://192.168.43.131:8080/postInfo/findPostById?userId=" + Constant.userId)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("okhttp","请求失败");
                e.printStackTrace();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //处理后端传递的数据
                Log.e("okhttp","请求成功");
                String responseDate = response.body().string();
                Log.e("返回的数据",responseDate);
                //数据源发送改变，需要更新界面，使用Handler
                Message message = new Message();
                message.obj = responseDate;
                message.arg1 = 3;
                myHandler.sendMessage(message);//发送到主线程的消息队列
            }
        });
    }

}
